<?php

namespace app\service;


class QCloudCosService
{
    const HTTP_NAME = 'https';

    public static ?QCloudCosService $_instance = null;

    // SECRETID和SECRETKEY请登录访问管理控制台进行查看和管理
    //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
    private string $secretId = 'AKIDDI7yYw6RntiGYYJn';
    //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
    private string $secretKey = 'I7fvuc3mrgFbib';
    //替换为用户的 region，已创建桶归属的region可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
    private string $region = 'ap-shanghai';
    private string $bucket = 'OwenWeb-125641';

    /**
     * @return QCloudCosService|mixed
     */
    public static function instance(): ?QCloudCosService
    {
        if (!static::$_instance) static::$_instance = new self();
        return static::$_instance;
    }

    /**
     * 上传文件
     *
     * @param \Webman\Http\UploadFile $file
     *
     * @return array
     * @throws \Exception
     * @author OwenZhang
     * @date   2022-04-16 23:46:28
     *
     */
    public function upload(\Webman\Http\UploadFile $file): array
    {
        $filePath = config('app.project', 'webman-admin') . '/' . $file->getUploadExtension() . '/' . date('Ymd') . '/' . uniqid() . '.' . $file->getUploadExtension();
        $fileName = $file->getPathName();

        // SECRETID和SECRETKEY请登录访问管理控制台进行查看和管理
        //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretId = $this->secretId;
        //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = $this->secretKey;
        //替换为用户的 region，已创建桶归属的region可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $region = $this->region;
        $bucket = $this->bucket;

        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => self::HTTP_NAME, //协议头部，默认为http
                'credentials' => array(
                    'secretId' => $secretId,
                    'secretKey' => $secretKey
                )
            ));

        try {
            $result = $cosClient->putObject(array(
                'Bucket' => $bucket,
                'Key' => $filePath,
                'Body' => fopen($fileName, 'rb'),
                'ServerSideEncryption' => 'AES256'
            ));
        } catch (\Exception $e) {
            throw new \Exception($e, 500);
        }

        if (!isset($result['Location'])) {
            throw new \Exception('上传失败', 500);
        }

        return [
            'name' => $file->getUploadName(),
            'href' => self::HTTP_NAME . '://' . $result['Location'],
            'mime' => $file->getUploadMineType(),
            'size' => byte_size($file->getSize()),
            'type' => 4,
            'ext' => $file->getUploadExtension(),
        ];
    }

    /**
     * 删除文件
     *
     * @param string $key
     *
     * @return boolean
     * @throws \Exception
     * @author OwenZhang
     * @date   2022-04-17 00:06:50
     *
     */
    public function delete(string $key): bool
    {
        if (strpos($key, 'myqcloud.com/') !== false) $key = getLaterString($key, '.com/');

        // SECRETID和SECRETKEY请登录访问管理控制台进行查看和管理
        //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretId = $this->secretId;
        //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = $this->secretKey;
        //替换为用户的 region，已创建桶归属的region可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $region = $this->region;
        $bucket = $this->bucket;

        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => self::HTTP_NAME, //协议头部，默认为http
                'credentials' => array(
                    'secretId' => $secretId,
                    'secretKey' => $secretKey
                )
            ));

        try {
            $result = $cosClient->deleteObject(array(
                'Bucket' => $bucket, //存储桶名称，由BucketName-Appid 组成，可以在COS控制台查看 https://console.cloud.tencent.com/cos5/bucket
                'Key' => $key //若多路径则写为folder/exampleobject，不要在第一层带/，否则删除会失败
            ));
        } catch (\Exception $e) {
            throw new \Exception($e, 500);
        }

        if (!isset($result['Location'])) {
            throw new \Exception('删除失败', 500);
        }

        return true;
    }
}
